//
//  SGSProfileROViewController.m
//  AgileNYC
//
//  Created by German on 01.08.14.
//  Copyright (c) 2014 Softlegion. All rights reserved.
//

#import "SGSProfileROViewController.h"
#import "SGSModelsManager.h"
#import "SGSUtils.h"
#import "SGSAppConsts.h"
#import "SGSDelegatesManager.h"

@interface SGSProfileROViewController () <UIActionSheetDelegate, ABNewPersonViewControllerDelegate>



@end

@implementation SGSProfileROViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.pnlAcceptIgnoreButtons.hidden = !self.isRequestProfile;
    self.pnlNavigationBar.hidden = self.isRequestProfile;
    
    self.pnlAcceptIgnoreButtons.backgroundColor = [UIColor whiteColor];

    if (self.isRequestProfile) {
        
        self.pnlProfileInfoView.frame = CGRectMake(self.pnlProfileInfoView.frame.origin.x,
                                               self.pnlNavigationBar.frame.origin.y,
                                               self.pnlProfileInfoView.frame.size.width,
                                               self.pnlProfileInfoView.frame.size.height + self.pnlNavigationBar.frame.size.height - 3);

    } else {
        self.pnlProfileInfoView.frame = CGRectMake(self.pnlProfileInfoView.frame.origin.x,
                                                   self.pnlNavigationBar.frame.origin.y + self.pnlNavigationBar.frame.size.height + 1,
                                                   self.pnlProfileInfoView.frame.size.width,
                                                   self.pnlProfileInfoView.frame.size.height + self.pnlAcceptIgnoreButtons.frame.size.height);
    }
    
}

#pragma mark - Actions

- (IBAction)onAcceptButtonPress:(id)sender {
    
    SGSDelegatesManager * delegatesManager = [SGSDelegatesManager sharedDelegatesManager];
    
    if (delegatesManager.currentEventsVC) {
        [delegatesManager.currentEventsVC replyConnectionRequest:YES];
        //[self.navigationController popToViewController:delegatesManager.currentEventsVC animated:YES];
    } else {
        SGSEventsViewController * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"SGSEventsViewController"];

        [vc replyConnectionRequest:YES];
        
        //[self.navigationController pushViewController:vc animated:YES];
    }

    
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)onIgnoreButtonPress:(id)sender {
    
    SGSDelegatesManager * delegatesManager = [SGSDelegatesManager sharedDelegatesManager];
    
    if (delegatesManager.currentEventsVC) {
        [delegatesManager.currentEventsVC replyConnectionRequest:NO];
        //[self.navigationController popToViewController:delegatesManager.currentEventsVC animated:YES];
    } else {
        SGSEventsViewController * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"SGSEventsViewController"];
        
        [vc replyConnectionRequest:NO];
        
        //[self.navigationController pushViewController:vc animated:YES];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)onSaveToContactButtonClick:(id)sender {
    /*UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:Cancel_Button_Title
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:Save_To_PhoneBook_Button_Title,nil];
    
    [actionSheet showInView:self.view];*/
    [self saveCurrentUserToPhoneBook];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:Save_To_PhoneBook_Button_Title]) {
        //[self saveContactData];
        [self saveCurrentUserToPhoneBook];
    }
}

-(void) saveCurrentUserToPhoneBook {
    SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
    
    GSUser * currContact = modelsManager.currentContact;
    //CFErrorRef  anError = NULL;
    
    if (ABAddressBookRequestAccessWithCompletion) {
        
        CFErrorRef err;
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &err);
        
        /*if ((err) && (err!=0x4066600000000000)) {
         // handle error
         //GSLog(GSLogError, @"[onSaveToContactButtonClick] Error: %@", err);
         //CFRelease(err);
         return;
         }*/
        
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            // ABAddressBook doesn't gaurantee execution of this block on main thread, but we want our callbacks to be
            dispatch_async(dispatch_get_main_queue(), ^{
                if (!granted) {
                    //failure((__bridge NSError *)error);
                } else {
                    //readAddressBookContacts(addressBook, success);
                    ABRecordRef person = ABPersonCreate();
                    
                    ABPersonSetImageData(person, (__bridge CFDataRef)currContact.photo, nil);
                    
                    ABRecordSetValue(person, kABPersonFirstNameProperty, (__bridge CFTypeRef)(currContact.firstName), nil);
                    ABRecordSetValue(person, kABPersonLastNameProperty, (__bridge CFTypeRef)(currContact.lastName), nil);
                    ABRecordSetValue(person, kABPersonOrganizationProperty, (__bridge CFTypeRef)(currContact.company), nil);
                    ABRecordSetValue(person, kABPersonJobTitleProperty, (__bridge CFTypeRef)(currContact.title), nil);
                    ABRecordSetValue(person, kABPersonNoteProperty, (__bridge CFTypeRef)(currContact.notes), nil);
                    
                    ABMutableMultiValueRef multiAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
                    NSMutableDictionary *addressDictionary = [[NSMutableDictionary alloc] init];
                    
                    [addressDictionary setObject:currContact.city forKey:(NSString *)kABPersonAddressCityKey];
                    [addressDictionary setObject:currContact.state forKey:(NSString *)kABPersonAddressStateKey];
                    
                    ABMultiValueAddValueAndLabel(multiAddress, (__bridge CFTypeRef)(addressDictionary), (CFStringRef)@"Address", NULL);
                    ABRecordSetValue(person, kABPersonAddressProperty, multiAddress,nil);
                    CFRelease(multiAddress);

                    ABMutableMultiValueRef phoneMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
                    ABMultiValueAddValueAndLabel(phoneMultiValue, (__bridge CFTypeRef)(currContact.phone), (CFStringRef)@"Phone", NULL);
                    ABRecordSetValue(person, kABPersonPhoneProperty, phoneMultiValue, nil);
                    
                    ABMutableMultiValueRef websiteMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
                    ABMultiValueAddValueAndLabel(websiteMultiValue, (__bridge CFTypeRef)(currContact.webSite), (CFStringRef)@"Website", NULL);
                    ABRecordSetValue(person, kABPersonURLProperty, websiteMultiValue, nil);
                    
                    ABMutableMultiValueRef emailMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
                    ABMultiValueAddValueAndLabel(emailMultiValue, (__bridge CFTypeRef)(currContact.eMail), (CFStringRef)@"Email", NULL);
                    ABRecordSetValue(person, kABPersonEmailProperty, emailMultiValue, nil);
                    
                    if ((currContact.facebookId) && ([currContact.facebookId length]>0)){
                        ABMutableMultiValueRef multiSocial = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
                        NSMutableDictionary *socialDictionary = [[NSMutableDictionary alloc] init];
                        
                        NSString * socialName = @"";
                        
                        if ((currContact.facebookName) && ([currContact.facebookName length]>0)) {
                            socialName =currContact.facebookName;
                        } else if ([currContact.fullName length]>0) {
                            socialName =currContact.fullName;
                        } else {
                            socialName =currContact.facebookId;
                        }
                        
                        NSString *url = [NSString stringWithFormat:@"https://facebook.com/%@",currContact.facebookId];
                        
                        [socialDictionary setObject:socialName forKey:(NSString *)kABPersonSocialProfileUsernameKey];
                        [socialDictionary setObject:url forKey:(NSString *)kABPersonSocialProfileURLKey];
                        [socialDictionary setObject:@"Facebook" forKey:(NSString *)kABPersonSocialProfileServiceKey];

                        ABMultiValueAddValueAndLabel(multiSocial, (__bridge CFTypeRef)(socialDictionary), (CFStringRef)@"Facebook", NULL);
                        ABRecordSetValue(person, kABPersonSocialProfileProperty, multiSocial,nil);
                        CFRelease(multiSocial);

                    }

                    if ((currContact.googlePlusId) && ([currContact.googlePlusId length]>0)){
                        ABMutableMultiValueRef multiSocial = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
                        NSMutableDictionary *socialDictionary = [[NSMutableDictionary alloc] init];
                        
                        NSString * socialName = @"";
                        
                        if ((currContact.googlePlusName) && ([currContact.googlePlusName length]>0)) {
                            socialName =currContact.googlePlusName;
                        } else if ([currContact.fullName length]>0) {
                            socialName =currContact.fullName;
                        } else {
                            socialName =currContact.googlePlusId;
                        }
                        
                        NSString *url = [NSString stringWithFormat:@"https://plus.google.com/%@",currContact.googlePlusId];
                        
                        [socialDictionary setObject:socialName forKey:(NSString *)kABPersonSocialProfileUsernameKey];
                        [socialDictionary setObject:url forKey:(NSString *)kABPersonSocialProfileURLKey];
                        [socialDictionary setObject:@"Google+" forKey:(NSString *)kABPersonSocialProfileServiceKey];
                        
                        ABMultiValueAddValueAndLabel(multiSocial, (__bridge CFTypeRef)(socialDictionary), (CFStringRef)@"Google+", NULL);
                        ABRecordSetValue(person, kABPersonSocialProfileProperty, multiSocial,nil);
                        CFRelease(multiSocial);
                        
                    }
                    
                    if ((currContact.linkedInId) && ([currContact.linkedInId length]>0)){
                        ABMutableMultiValueRef multiSocial = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
                        NSMutableDictionary *socialDictionary = [[NSMutableDictionary alloc] init];
                        
                        NSString * socialName = @"";
                        
                        if ((currContact.linkedInName) && ([currContact.linkedInName length]>0)) {
                            socialName =currContact.linkedInName;
                        } else if ([currContact.fullName length]>0) {
                            socialName =currContact.fullName;
                        } else {
                            socialName =currContact.linkedInId;
                        }
                        
                        NSString *url = [NSString stringWithFormat:@"%@",currContact.linkedInId];
                        
                        [socialDictionary setObject:socialName forKey:(NSString *)kABPersonSocialProfileUsernameKey];
                        [socialDictionary setObject:url forKey:(NSString *)kABPersonSocialProfileURLKey];
                        [socialDictionary setObject:@"LinkedIn" forKey:(NSString *)kABPersonSocialProfileServiceKey];
                        
                        ABMultiValueAddValueAndLabel(multiSocial, (__bridge CFTypeRef)(socialDictionary), (CFStringRef)@"LinkedIn", NULL);
                        ABRecordSetValue(person, kABPersonSocialProfileProperty, multiSocial,nil);
                        CFRelease(multiSocial);
                        
                    }


                    /*ABAddressBookAddRecord(addressBook, person, &anError);
                     ABAddressBookSave (addressBook,&anError);*/
                    
                    //ABAddressBookAddRecord(addressBook, person, nil);
                    //ABAddressBookSave (addressBook,nil);
                    
                    ABNewPersonViewController *picker = [[ABNewPersonViewController alloc] init];
                    picker.newPersonViewDelegate = self;
                    picker.displayedPerson = person;
                    picker.addressBook = addressBook;
                    // Allow users to edit the person’s information
                    //picker.allowsEditing = YES;
                    picker.navigationItem.title=@"Edit Contact";
                    [self.navigationController setNavigationBarHidden:NO animated:YES];
                    [self.navigationController pushViewController:picker animated:YES];
                    //[self presentModalViewController:picker animated:YES];
                    //CFRelease(phoneMultiValue);
                    //CFRelease(websiteMultiValue);
                    //CFRelease(emailMultiValue);
                    //CFRelease(person);
                    
                }
                CFRelease(addressBook);
            });
        });
    } else {
        //ABAddressBookRef addressBook = ABAddressBookCreate();
        //readAddressBookContacts(addressBook, success);
        //CFRelease(addressBook);
    }
}

- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person {
    ABAddressBookAddRecord(newPersonView.addressBook, person, nil);
    ABAddressBookSave (newPersonView.addressBook,nil);

    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)onBackButtonPress:(UIButton *)sender {
  [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - System Functions

- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];}


@end
